#pragma once
#include <iostream>
#include "InetAddr.hpp"
#include <functional>
#include "Socket.hpp"
#include "Protocol.hpp"
#include "Connection.hpp"
using process_t = std::function<std::shared_ptr<Response>(std::shared_ptr<Request>)>;
class PackageParse
{
public:
    PackageParse(process_t process) : _process(process)
    {
    }
    void Excute(Connection *conn)
    {
        LOG(INFO, "process message\n");
        string packagestreamqueue;
        while (1)
        {
            string jsonstr = Decode(conn->Inbuff());
            if (jsonstr == "")
            {
                break;
            }
            cout << "get:" << jsonstr << endl;
            // 获取到完整的报文
            auto req = Factory::BuildRequest();
            // 反序列化
            req->Deserialize(jsonstr);
            // 业务处理
            auto resp = _process(req);
            // 序列化应答
            string respjson;
            resp->Serialize(&respjson);
            respjson = Encode(respjson);
            cout << "result:" << respjson << endl;
            cout << "-----------------------" << endl;
            conn->AppendOutbuffer(respjson);
        }

        // 发送应答
        // 方法一，直接发送，高效
        // 至少一个应答
        if (!conn->Outbuff().empty())
            conn->_handler_sender(conn);
        // 方法二，不发送，然后激活写事件（多线程必须用，保证顺序问题）
        //  if(!conn->Outbuff().empty())
        //  {
        //      conn->_R->EnableConnectionReadWrite(conn->Sockfd(), true, true);
        //  }
    }
    ~PackageParse()
    {
    }

private:
    process_t _process;
};
